package com.api.oa.services.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.api.oa.common.RequestStatus;
import com.api.oa.common.UserType;
import com.api.oa.config.UserContext;
import com.api.oa.mapper.*;
import com.api.oa.model.entity.YQCase;
import com.api.oa.model.entity.YQPatient;
import com.api.oa.model.entity.YQRequest;
import com.api.oa.model.entity.YQUser;
import com.api.oa.model.params.YQRequestParams;
import com.api.oa.model.vo.OaOrgTreeVO;
import com.api.oa.model.vo.YQInsEntityVO;
import com.api.oa.model.vo.YQRequestVO;
import com.api.oa.services.YQRequestService;
import com.api.shopapi.entity.MyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class YQRequestServiceImpl implements YQRequestService {

    @Autowired
    private YQRequestMapper mapper;

    @Autowired
    private YQPatientMapper yqPatientMapper;

    @Autowired
    private YQUserMapper yqUserMapper;

    @Autowired
    private YQCaseMapper yqCaseMapper;

    @Autowired
    private YQInsEntityMapper yqInsEntityMapper;

    @Value("${server.port}")
    protected String port;

    @Override
    public Integer add(YQRequest entity) throws Exception {
        if (!IdcardUtil.isValidCard(entity.getRequestIdCard())) {
            throw new Exception("身份证件不合法");
        }
//        YQPatient oneByIdCard = yqPatientMapper.findOneByIdCard(entity.getRequestIdCard());
//        if (oneByIdCard != null) {
//            throw new Exception(entity.getRequestIdCard() + "身份证已经评定上了，不能重复评定");
//        }
        //申请者是否评估中 是不可以在申请
//        YQRequestVO byIdCard = mapper.findByIdCard(entity.getRequestIdCard());
//        if (byIdCard != null) throw  new Exception("身份证号已经被占用");
        YQPatient oneByIdCard = yqPatientMapper.findOneByIdCard(entity.getRequestIdCard());
        if (oneByIdCard != null) throw new Exception("身份证号已经被占用");
        Integer one = mapper.isRequesting(entity.getRequestIdCard());
        if (one == 1) {
            throw new Exception(entity.getRequestIdCard() + "身份证已经申请过,且正在评估中");
        }
        if (UserContext.getRole() == UserType.INS) {
            YQInsEntityVO oneByInsCode = yqInsEntityMapper.findOneByInsCode(UserContext.getInsCode());
            entity.setInsUserId(UserContext.getUserId());
            entity.setRequestIns(UserContext.getInsCode());
            entity.setInsName(oneByInsCode == null ? "" : oneByInsCode.getInsName());
        }
        entity.setOrderCode(IdUtil.randomUUID());
        entity.setCreatedAt(DateUtil.date());
        return mapper.insert(entity);
    }

    @Override
    public void remove(String id) {
        mapper.delete(id);
    }

    @Override
    public Integer update(YQRequest entity) throws Exception {
        return mapper.update(entity);
    }


    //web
    @Override
    public PageInfo<YQRequestVO> list(String insCode, String idCard, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc,orderCode desc");
        if (UserContext.getRole() == UserType.INS) {  //机构
            return new PageInfo<>(mapper.listIns(idCard, UserContext.getUserId(), null, null));
        } else if (UserContext.getRole() == UserType.INS_ASS) { //监管
            return new PageInfo<>(mapper.listIns(idCard, null, null, UserContext.getUserId()));
        } else if (UserContext.getRole() == UserType.GOV) { //政府
            return new PageInfo<>(mapper.listGov(idCard, null, null, null, insCode));
        } else if (UserContext.getRole() == UserType.GOV_ASS) { //政府监管
            return new PageInfo<>(mapper.listGov(idCard, null, null, UserContext.getUserId(), insCode));
        }
        return new PageInfo<>();
    }

    /**
     * 安卓
     *
     * @param idCard
     * @param inUserId
     * @param status
     * @param assUserId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<YQRequestVO> queryByIdCardIns(String idCard, Long inUserId, Long status, Long assUserId, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc");
        return new PageInfo<>(mapper.queryByIdCardIns(idCard, inUserId, status, assUserId));
    }

    /**
     * 安卓
     *
     * @param idCard
     * @param insUserId
     * @param isAss
     * @param assUserId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<YQRequestVO> queryByIdCardGov(String idCard, Long insUserId, Boolean isAss, Long assUserId, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc");
        return new PageInfo<>(mapper.queryByIdCardGov(idCard, insUserId, isAss, assUserId));
    }

    @Override
    public YQRequestVO one(String id) {
        YQRequestVO one = mapper.findOne(id);
        List<YQCase> yqCases = yqCaseMapper.listByOrder(id);
        one.setUrls(yqCases.stream().map(i -> i.getCaseUrl()).collect(Collectors.toList()));
        return one;
    }

    private String getFileUrl() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String fileUrl = "http://" + address.getHostAddress() + ":" + port;
            return fileUrl;
        } catch (UnknownHostException e) {
            return "";
        }
    }

    @Override
    public Integer assessmentIns(YQRequestParams entity) throws Exception {
        if (entity.getIsPass()) {
            YQRequestVO one = mapper.findOne(entity.getOrderCode());
            if (one == null) throw new Exception("请求单不存在");
            if (one.getStatus() != RequestStatus.PER_ASS_ING) throw new Exception("申请单当前状态不对");
            YQPatient oneByIdCard = yqPatientMapper.findOneByIdCard(one.getRequestIdCard());
            if (oneByIdCard != null) {
                throw new Exception(entity.getRequestIdCard() + "身份证已经评定上了，不能重复评定");
            }

            oneByIdCard = new YQPatient();
            oneByIdCard.setPatientPhone(one.getContacts());
            oneByIdCard.setPatientIdCard(one.getRequestIdCard());
            oneByIdCard.setPatientName(one.getRequestName());
            oneByIdCard.setPatientSex(one.getRequestSex());
            oneByIdCard.setIdCardType(one.getIdCardType());
            oneByIdCard.setLat(one.getLat());
            oneByIdCard.setLng(one.getLng());
            oneByIdCard.setPatientIns(one.getRequestIns());
            oneByIdCard.setPatientAddress(one.getPatientAddress()); //地址不难丢下
            oneByIdCard.setPatientAddBed(entity.getPatientAddBed());
            oneByIdCard.setPatientType(entity.getPatientType());
            oneByIdCard.setPatientLevel(entity.getPatientLevel());
            oneByIdCard.setAttendType(entity.getAttendType());
            oneByIdCard.setDisabled(entity.getDisabled());

            oneByIdCard.setConditionDesc(one.getConditionDesc());
            yqPatientMapper.insert(oneByIdCard);
            //设置账号的所属机构
            yqUserMapper.updateBelongInsCode(one.getRequestIns(), one.getUserId());
            return mapper.updateStatus(RequestStatus.INS_ASS_ED, entity.getOrderCode());
        } else {
            //不通过
            return mapper.updateStatus(RequestStatus.REJECT_ASS_ING, entity.getOrderCode());
        }
    }

    @Override
    public YQRequest findOneByUserId(Long userId) {
        return mapper.findOneByUserId(userId);
    }

    @Override
    public Integer updateLocation(Double lat, Double lng, String id) {
        return mapper.updateLocation(lat, lng, id);
    }

    @Override
    @Transactional
    public Integer requestGov(YQRequest entity) throws Exception {
        YQUser oneByIDCard = yqUserMapper.findOneByIDCard(entity.getRequestIdCard());
        if (oneByIDCard != null) throw new Exception("身份证号已经被占用");
        Integer one = mapper.isRequesting(entity.getRequestIdCard());
        if (one == 1) {
            throw new Exception(entity.getRequestIdCard() + "身份证已经申请过,且正在评估中");
        }
        if (StrUtil.isBlank(entity.getRequestIns()) || StrUtil.isBlank(entity.getInsName())) {
            YQInsEntityVO oneByInsCode = yqInsEntityMapper.findOneByInsCode(UserContext.getInsCode());
            entity.setRequestIns(UserContext.getInsCode());
            entity.setInsName(oneByInsCode.getInsName());
        }
        YQUser yqUser = new YQUser();
        yqUser.setCreatedAt(DateUtil.date());
        yqUser.setUname(entity.getRequestName());
        yqUser.setIdCard(entity.getRequestIdCard());
        yqUser.setBelongInsCode(entity.getRequestIns());
        yqUser.setPasswd(SecureUtil.md5("123456"));
        yqUser.setPhone(entity.getContacts());
        yqUserMapper.insert(yqUser);
        entity.setUserId(yqUser.getUserId());
        return this.add(entity);
    }

    @Override
    public PageInfo<YQRequest> request(String insCode, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("createdAt desc");
        return new PageInfo<>(mapper.requests(insCode));
    }


}
